package org.road0329.dlt698.axdr;

import org.road0329.dlt698.ReverseByteArrayInputStream;
import org.road0329.dlt698.ReverseByteArrayOutputStream;
import org.road0329.dlt698.asn1.axdr.AxdrType;

import java.io.IOException;
import java.nio.ByteBuffer;

public class RN_MAC extends AxdrType {
    private ByteBuffer dataCode = null;
    private RN rn = null;
    private MAC mac = null;

    public RN_MAC() {
    }

    public void setDataCode(ByteBuffer dataCode) {
        this.dataCode = dataCode;
    }

    public void setAll(RN rn, MAC mac) {
        this.rn = rn;
        this.mac = mac;
    }

    public void setRn(RN rn) {
        this.rn = rn;
    }

    public void setMac(MAC mac) {
        this.mac = mac;
    }

    public int decode(ReverseByteArrayInputStream input) throws Exception {
        int codeLength = 0;
        this.rn = new RN();
        codeLength += this.rn.decode(input);
        this.mac = new MAC();
        codeLength += this.mac.decode(input);
        return codeLength;
    }

    public int encode(ReverseByteArrayOutputStream output) throws Exception {
        int codeLength;
        if (this.dataCode != null) {
            codeLength = this.dataCode.remaining();
            while (this.dataCode.hasRemaining()) {
                output.write(this.dataCode.get());
            }
        } else {
            if (this.rn != null && this.mac != null) {
                codeLength = 0;
                codeLength += this.mac.encode(output);
                codeLength += this.rn.encode(output);
            } else {
                throw new IllegalStateException("rn or mac is null");
            }
        }
        return codeLength;
    }

    public void encodeAndSave(int encodingSizeGuess) throws Exception {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = ByteBuffer.wrap(revOStream.toByteArray());
    }

    @Override
    public String toString() {
        if (this.rn != null && this.mac != null) {
            return "sequence: {" + "rn: " + this.rn + ", mac: " + this.mac + "}";
        } else {
            return "rn || mac is null";
        }
    }
}



